<?php
namespace app\common;

use Yii;
use app\common\ErrorCode;

/**
* 处理微信小程序登陆的类
*/

class Deal
{
	
	public function getLogininfo( $code )
	{
        //将参数填写到URL
        $grant_type = 'authorization_code';
        $APPID = YII::$app->params['WECHAT']['APPID'];
        $APPSECRET = YII::$app->params['WECHAT']['APPSECRET'];
        $url_openId = YII::$app->params['URL']['OPENID'].'?appid='.$APPID.'&secret='.$APPSECRET.'&js_code='.$code.'&grant_type='.$grant_type;
        $curl = curl_init(); //初始化
		curl_setopt($curl, CURLOPT_URL, $url_openId);//指定请求的url 
		curl_setopt($curl, CURLOPT_HEADER, 0); //不返回HTTP头部信息
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //指定url返回的类型 1则为string
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//跳过证书检查
		//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
		$result = curl_exec($curl);
		curl_close($curl); 
		return json_decode($result,JSON_FORCE_OBJECT); 
	}

    //微信用户信息获取
	public function getUserinfo( $sessionKey, $encryptedData, $iv )
	{
		$APPID = YII::$app->params['WECHAT']['APPID'];

		if (strlen($sessionKey) != 24) {
			return ErrorCode::$IllegalAesKey;
		}
		$aesKey=base64_decode($sessionKey);

		if (strlen($iv) != 24) {
			return ErrorCode::$IllegalIv;
		}
		$aesIV=base64_decode($iv);

		$aesCipher=base64_decode($encryptedData);

		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

		$dataObj=json_decode( $result , JSON_FORCE_OBJECT);
		if( $dataObj  == NULL )
		{
			return ErrorCode::$IllegalBuffer;
		}
		
		$data = $dataObj;
		if( $data['nickName'] == Null ){
			$data = ErrorCode::$nickName;
		}else if( $data['avatarUrl'] == Null ){
			$data =  ErrorCode::$avatarUrl;
		}else if( $data['nickName'] == Null && $data['avatarUrl'] == Null ){
			$data = ErrorCode::$dataNull;
		}
		return $data;
	}

	//负责生成3rdsession的函数
	public function _3rd_session( $len )
    {
        $fp = @fopen('/dev/urandom', 'rb');
        $result = '';
        if ($fp !== FALSE) {
            $result .= @fread($fp, $len);
            @fclose($fp);
        } else {
            trigger_error('Can not open /dev/urandom.'); 
        }
        // convert from binary to string
        $result = base64_encode($result);
        // remove none url chars
        $result = strtr($result, '+/', '-_');
        $result = substr($result, 0, $len);
        return $result;
    }
}
